package com.swxy.club.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.swxy.club.dto.Club;
import com.swxy.club.dto.ClubApplication;
import com.swxy.club.dto.ClubUserRole;
import com.swxy.club.dto.User;
import com.swxy.club.dto.bo.CurrentUserBO;
import com.swxy.club.dto.dt.ClubApprovalQueryDTO;
import com.swxy.club.dto.Vo.ClubApprovalDetailVO;
import com.swxy.club.dto.Vo.ClubApprovalVO;
import com.swxy.club.dto.dt.ClubRoleConstants;
import com.swxy.club.enums.AuditStatus;
import com.swxy.club.enums.ClubStatus;
import com.swxy.club.feignClient.UserServiceFeignClient;
import com.swxy.club.mapper.ClubApplicationMapper;
import com.swxy.club.mapper.ClubMapper;

import com.swxy.club.mapper.ClubUserRoleMapper;
import com.swxy.club.result.Result;
import com.swxy.club.service.ClubApplicationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swxy.club.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 社团申请记录表 服务实现类
 * </p>
 *
 * @author dyh
 * @since 2025-04-23
 */
@Service
@RequiredArgsConstructor
public class ClubApplicationServiceImpl extends ServiceImpl<ClubApplicationMapper, ClubApplication> implements ClubApplicationService {
    @Autowired
    private  ClubMapper clubMapper;

    @Autowired
    private ClubUserRoleMapper clubUserRoleMapper;

    private final UserServiceFeignClient userServiceFeignClient;

    /**
     * 根据id查询审批详情
     * @param id
     * @return
     */
    @Override
    public ClubApprovalDetailVO getApprovalDetail(Long id) {
        // 1. 根据id查询审批记录
        ClubApplication application = this.getBaseMapper().selectById(id);

        // 2. 转换为审批详情VO
        ClubApprovalDetailVO vo = new ClubApprovalDetailVO();
        vo.setId(application.getId());
        vo.setApplyReason(application.getApplyReason());
        vo.setStatus(application.getStatus());
        vo.setApplyTime(application.getCreateTime());
        // 查询社团名称
        Club club = clubMapper.selectById(application.getCulbId());
        if (club != null) {
            vo.setClubName(club.getName());
            vo.setClubId(club.getClubId());
        }
        CurrentUserBO currentUser = UserContext.getCurrentUser();
        Assert.notNull(currentUser, "用户不存在");
        vo.setApplicantName(currentUser.getRealName());
        vo.setUserId(currentUser.getId());
        return vo;
    }

    /**
     * 审批申请
     * @param approvalId
     * @param isApproved
     * @param refuseReason
     */
    @Transactional
    @Override
    public void processApproval(Long approvalId, Boolean isApproved, String refuseReason) {
        // 从token中获取操作人ID
        CurrentUserBO currentUser = UserContext.getCurrentUser();
        Long currentUserId = currentUser.getId();
        // 查询审批记录
        ClubApplication application = this.getBaseMapper().selectById(approvalId);
        if (application == null) {
           Assert.notNull(application, "审批记录不存在");
        }

        //  检查当前状态
        if (!"PENDING".equals(application.getStatus())) {
            Assert.notNull(application, "审批记录状态不允许修改");
        }

        // 3查询关联社团
        Club club = clubMapper.selectById(application.getCulbId());
        if (club == null) {
            Assert.notNull(club, "社团不存在");
        }

        // 4. 处理审批结果
        if (isApproved) {
            // 审批通过
            application.setStatus(AuditStatus.APPROVED);
            // 更新社团审批状态
            club.setAppliStatus(AuditStatus.APPROVED);
            // 设置社团为活跃状态
            club.setStatus(ClubStatus.ACTIVE);
//            将社团创建者设置为社长,并且直接加入社团
            ClubUserRole newPresident = new ClubUserRole();
            newPresident.setClubId(club.getClubId().intValue());
            newPresident.setUserId(application.getUserId().intValue());
            newPresident.setRoleCode(ClubRoleConstants.PRESIDENT);
            newPresident.setCreateId((long) application.getUserId().intValue());
            newPresident.setCreateTime(LocalDateTime.now());
            clubUserRoleMapper.insert(newPresident);
        }
        else {
            // 审批拒绝
            if (StringUtils.isBlank(refuseReason)) {
                Assert.notNull(refuseReason, "拒绝原因不能为空");
            }
            application.setStatus(AuditStatus.REJECTED);
            application.setRefuseReason(refuseReason); // 设置拒绝原因
            club.setAppliStatus(AuditStatus.REJECTED); // 更新社团审批状态
            // 社团状态保持不变
        }

        // 更新操作信息

        application.setOperateId(Math.toIntExact(currentUserId));
        application.setUpdateTime(LocalDateTime.now());

        // 6. 保存更改
        this.getBaseMapper().updateById(application);
        clubMapper.updateById(club);
    }

    @Override
    @Transactional
    public Page<ClubApprovalVO> getApprovalPage(ClubApprovalQueryDTO queryDTO) {
        // 创建分页对象
        Page<ClubApprovalVO> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<ClubApplication> queryWrapper = new LambdaQueryWrapper<>();

        // 审批状态条件
        if (StringUtils.isNotBlank(queryDTO.getStatus())) {
            queryWrapper.eq(ClubApplication::getStatus, queryDTO.getStatus());
        }

        // 社团名称模糊查询
        if (StringUtils.isNotBlank(queryDTO.getClubName())) {
            // 先查询符合条件的社团ID列表
            LambdaQueryWrapper<Club> clubQuery = new LambdaQueryWrapper<>();
            clubQuery.like(Club::getName, queryDTO.getClubName());
            List<Long> clubIds = clubMapper.selectList(clubQuery)
                    .stream()
                    .map(Club::getClubId)
                    .collect(Collectors.toList());

            if (!clubIds.isEmpty()) {
                queryWrapper.in(ClubApplication::getCulbId, clubIds);
            } else {
                // 如果没有匹配的社团，直接返回空结果
                return page.setTotal(0);
            }
        }

        // 按申请时间倒序
        queryWrapper.orderByDesc(ClubApplication::getCreateTime);

        // 执行查询
        List<ClubApplication> applications = this.getBaseMapper().selectList(queryWrapper);
        List<ClubApprovalVO> approvalVOs = new ArrayList<>(applications.size());

        // 转换为VO
        for (ClubApplication application : applications) {
            ClubApprovalVO vo = new ClubApprovalVO();
            vo.setId(application.getId());
            vo.setApplyReason(application.getApplyReason());
            vo.setStatus(application.getStatus());
            vo.setApplyTime(application.getCreateTime());

            // 查询社团名称
            Club club = clubMapper.selectById(application.getCulbId());
            if (club != null) {
                vo.setClubName(club.getName());
            }

            // 查询申请人姓名
            Result user1 = userServiceFeignClient.getUser(application.getUserId());
            User user = Convert.convert(User.class, user1.getData());
            if (user != null) {
                vo.setApplicant(user.getRealName());
            }

            approvalVOs.add(vo);
        }
        // 设置分页结果
        return page.setRecords(approvalVOs)
                .setTotal(approvalVOs.size());
    }
    }

